package com.mgs.product.tagger.dao
{
	import com.mgs.product.tagger.model.Document;
	
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	
	public class DocumentDaoImpl implements DocumentDao
	{
		public function DocumentDaoImpl()
		{
		}
		
		public function deleteDocument(repository:File, document:Document):void
		{
			if(document != null && document.file != null && document.file.exists)
			{
				document.file.deleteFile();
			}
		}
		
		public function createDocument(repository:File, document:Document):void
		{
			var docName:String = "UC" + (new Date().time) + "_" + document.name;
			document.uniqueCode = docName;
			var docFile:File = repository.resolvePath(docName);
			if(docFile.exists){
				throw new Error("file exists");
			}
			var stream:FileStream = new FileStream();
			stream.open(docFile, FileMode.WRITE);
			stream.close();
			document.file = docFile;
		}
		public function openDocument(repository:File, document:Document):void
		{
			repository
				.resolvePath(document.uniqueCode)
				.openWithDefaultApplication();
		}
		public function readDocumentContent(document:Document):String
		{
			var str:String;
			if(document != null && document.file != null && document.file.exists)
			{
				var stream:FileStream = new FileStream();
				stream.open(document.file, FileMode.READ);
				str = stream.readUTFBytes(document.file.size);
				stream.close();
			}
			return str;
		}
		public function writeDocumentContent(document:Document, content:String):void
		{
			if(document != null && document.file != null)
			{
				var stream:FileStream = new FileStream();
				stream.open(document.file, FileMode.WRITE);
				stream.writeUTFBytes(content);
				stream.close();
				document.content = content;
			}
		}
	}
}